package com.iocup.keybastion.spring.starter.filter;


import com.iocup.keybastion.core.HttpActionAdapter;
import com.iocup.keybastion.spring.starter.config.JeeWebContextHolder;
import com.iocup.keybastion.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SecurityLogicCheckerFilter implements Filter {

    private HttpActionAdapter httpActionAdapter;

    public SecurityLogicCheckerFilter(@Autowired HttpActionAdapter httpActionAdapter) {
        this.httpActionAdapter = httpActionAdapter;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {

        try {
            AuthUtils.getSecurityLogicChecker().handle(new JeeWebContextHolder((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse), webContextHolder -> {
                filterChain.doFilter(servletRequest, servletResponse);
                return null;
            }, httpActionAdapter);
        } catch (Exception e) {
            httpActionAdapter.adapt(e, new JeeWebContextHolder((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse));
        }
    }

    @Override
    public void destroy() {

    }
}
